#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json

import settings
import requests
try:
    import cookielib
except:
    import http.cookiejar as cookielib
import re
import time
import os.path
try:
    from PIL import Image
except:
    pass

# 构造 Request headers
agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36'
headers = {
    "Host": "www.zhihu.com",
    "Referer": "https://www.zhihu.com/",
    'User-Agent': agent
}

class login(object):
    def __init__(self, cookies_file_name):
        self.cookies_file_name = cookies_file_name
        self.headers = headers
        session = requests.session()
        session.cookies = cookielib.LWPCookieJar(filename=os.path.join(settings.ROOT_PATH, 'spiders/zhihu/cookies/%s' % cookies_file_name))
        try:
            session.cookies.load(ignore_discard=True, ignore_expires=True)
        except Exception as e:
            print(e)
            print("Cannot find cookie")
        # cookie_dict_list = json.loads(open(os.path.join(settings.ROOT_PATH, 'spiders/zhihu/cookies/%s' % cookies_file_name)).read())
        # cookie_jar = requests.cookies.RequestsCookieJar()
        # for d in cookie_dict_list:
        #     cookie_jar = requests.utils.cookiejar_from_dict(d, cookie_jar)
        # session.cookies = cookie_jar
        self.session = session

    def get_xsrf(self):
        '''_xsrf 是一个动态变化的参数'''
        index_url = 'https://www.zhihu.com'
        # 获取登录时需要用到的_xsrf
        index_page = self.session.get(index_url, headers=self.headers)
        # print(index_page.content.decode('utf-8'))
        html = index_page.text
        pattern = r'name="_xsrf" value="(.*?)"'
        # 这里的_xsrf 返回的是一个list
        _xsrf = re.findall(pattern, html)
        return _xsrf[0]

    # 获取验证码
    def get_captcha(self):
        t = str(int(time.time() * 1000))
        captcha_url = 'https://www.zhihu.com/captcha.gif?r=' + t + "&type=login"
        r = self.session.get(captcha_url, headers=self.headers)
        with open('captcha.jpg', 'wb') as f:
            f.write(r.content)
            f.close()
        # 用pillow 的 Image 显示验证码
        # 如果没有安装 pillow 到源代码所在的目录去找到验证码然后手动输入
        try:
            im = Image.open('captcha.jpg')
            im.show()
            im.close()
        except:
            print(u'请到 %s 目录找到captcha.jpg 手动输入' % os.path.abspath('captcha.jpg'))
        captcha = input("please input the captcha\n>")
        return captcha

    def isLogin(self):
        # 通过查看用户个人信息来判断是否已经登录
        url = "https://www.zhihu.com/settings/profile"
        login_code = self.session.get(url, headers=self.headers, allow_redirects=False).status_code
        if login_code == 200:
            return True
        else:
            return False

    def login(self, secret, account):
        _xsrf = self.get_xsrf()
        headers["X-Xsrftoken"] = _xsrf
        headers["X-Requested-With"] = "XMLHttpRequest"
        # 通过输入的用户名判断是否是手机号
        if re.match(r"^1\d{10}$", account):
            print("手机号登录 \n")
            post_url = 'https://www.zhihu.com/login/phone_num'
            postdata = {
                '_xsrf': _xsrf,
                'password': secret,
                'phone_num': account
            }
        else:
            if "@" in account:
                print("邮箱登录 \n")
            else:
                print("你的账号输入有问题，请重新登录")
                return 0
            post_url = 'https://www.zhihu.com/login/email'
            postdata = {
                '_xsrf': _xsrf,
                'password': secret,
                'email': account
            }
        # 不需要验证码直接登录成功
        login_page = self.session.post(post_url, data=postdata, headers=self.headers)
        if login_page.status_code != 200:
            raise Exception(login_page.content.decode('utf-8'))
        # print(login_page.text)
        login_code = login_page.json()
        if login_code['r'] == 1:
            # 不输入验证码登录失败
            # 使用需要输入验证码的方式登录
            postdata["captcha"] = self.get_captcha()
            login_page = self.session.post(post_url, data=postdata, headers=self.headers)
            login_code = login_page.json()
            print(login_code['msg'])
        # 保存 cookies 到文件，
        # 下次可以使用 cookie 直接登录，不需要输入账号和密码
        self.session.cookies.save()

if __name__ == '__main__':
    #
    forbbien_account = [('Hn3985kxs', '15818268397'), ('5t2uM8w8', '13509010733'), ('hh2sJf2C', '13829501411'), ('3m39HVU5', '17175257149'), ('K9DAY3V4', '15825535406')]

    account_2 = [('samgu1234', '13671549515'), ('samgu1234', '17701860110')]
    account_3 = [('g9H94AY3', '17187150644'), ('eYUeUucR', '17096655720')]
    account_4 = [('sw6qV88h', '17097350241'), ('et88d6Q6', '17187151490')]
    account_5 = [('psN344w4', '13064517926'), ('9Tr9Mx9F', '17174037436')]
    account_6 = [('39Rb88Rp', '17175253104'), ('bZtCXdX6', '17059978173')]
    account_7 = [('42Tvs5u5', '17174036431'), ('Bn2dXx2Q', '17092996619')]

    account_bk = [('FV8433s3', '17175254421')]
    # for i in account_1:
    #     a = login('%s_login' % i[1])
    #     if a.isLogin():
    #         print('%s logined' % i[1])
    #     else:
    #         a.login(*i)
    a = forbbien_account + account_bk
    for i in a:
        a = login('%s_login' % i[1])
        if a.isLogin():
            print('%s logined' % i[1])
        else:
            try:
                a.login(*i)
            except:
                pass

    # a = login('15818268397_login')
    # if a.isLogin():
    #     print('logined')
    # else:
    #     a.login('Hn3985kxs', '15818268397')